import {defineConfig, loadEnv} from 'vite'
import AutoImport from "unplugin-auto-import/vite"
import Components from 'unplugin-vue-components/vite';
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default ({ command, mode }: any) => {
  const env= loadEnv(mode, process.cwd() + "/env", 'VITE_')
  const config = defineConfig({
    plugins: [
      vue(),
      AutoImport ({
        //自动引入vue的ref、toRefs、onMounted等，无需在页面中再次引入
        imports: [
          "vue",
          "vue-router",
          "pinia",
          // 自定义预设
          {
            'vue-toastification': [
              // 命名导入
              'useToast', // import { useMouse } from '@vueuse/core',
              // 设置别名
              ['useToast', 'Toast'], // import { useFetch as useMyFetch } from '@vueuse/core',
            ]
          }
        ],
      }),
      Components({
        // 指定自动导入的组件位置，默认是 src/components
        dirs: ['src/components'],
      }),
    ],
    base: './', // 打包路径
    server: {
      port: parseInt(env.VITE_SERVER_PORT) // 服务端口号
    },
    resolve: {
      alias: {
        '@': resolve("./src"),
        '@c': resolve('./src/components'),
        '@v': resolve('./src/views')
      }
    },
    envDir: 'env',
    envPrefix: 'VITE_',
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/scss/variables.scss";'
        }
      }
    }
  })
  if (command === 'serve') {
    config.server!.proxy = {
      '/api': {
        target: env.VITE_API_BASE_URL_PROXY,
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '/api')
      }
    }
  }
  return config
}
